package hospital.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.jdbc.StringUtils;
import hospital.cmn.listener.DictListener;
import hospital.cmn.mapper.DictMapper;
import hospital.cmn.service.DictService;
import hospital.model.cmn.Dict;
import hospital.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author
 * @description:
 */
@Transactional
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    /**
     * @Author yang
     * @Description //TODO 根据数据id查询，子数据列表
     * @Param [id]
     * @return
     **/
    @Override
    //第一次查询，查询数据库，第二次查询查询缓存中
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        //父节点等于id，查询出子节点
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //判断查询出的节点集合，是否有子节点
        //向dictList 的每个dict对象中设置hasChildren
        for (Dict dict:dictList){
            boolean hasChild = this.isChild(dict.getId());
            dict.setHasChildren(hasChild);
            String data="2023-03-13 10:30:35";
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = sdf1.parse(data);
                dict.setCreateTime(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return dictList;
    }

    /**
     * @Author yang
     * @Description //TODO 导出数据字典接口
     * @Param [response]
     * @return
     **/
    @Override
    public void exportData(HttpServletResponse response) {
        //设置下载的设置
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //设置URLEncoder.encode 防止中文乱码
//        String fileName= URLEncoder.encode("数据字典","UTF-8");
        String fileName="dict";
        response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");


        //从数据库中得到数据
        List<Dict> list = baseMapper.selectList(null);
        //Dict 对象转成 DictEeVo
        List<DictEeVo> dictEeVoList=new ArrayList<>();
        for (Dict dict:list){
            DictEeVo vo=new DictEeVo();
            BeanUtils.copyProperties(dict,vo);
            dictEeVoList.add(vo);
        }
        //调用方法实现写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author yang
     * @Description //TODO 导入数据字典接口
     * @Param [file]
     * @return
     **/
    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importData(MultipartFile file) {
        try {
            //调用方法实现读入操作
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper))
            .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author yang
     * @Description //TODO //根据dictCode和Value查询医院等级接口 根据value值查询省市区接口
     * @Param [dictCode, value]
     * @return
     **/
    @Override
    public String getDictName(String dictCode, String value) {
        //根据value值查询省市区接口
        if(StringUtils.isNullOrEmpty(dictCode)){
            QueryWrapper<Dict> wrapper=new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else {
            //根据dictCode和Value查询医院等级接口

            //先根据dictCode得到父节点的id
            Dict dict = this.getDictByDictCode(dictCode);
            Long id = dict.getId();
            //通过parent_id 与value 查询出子节点的name
            QueryWrapper<Dict> wrapperChild=new QueryWrapper<>();
            wrapperChild.eq("parent_id",id);
            wrapperChild.eq("value",value);
            Dict dictChild = baseMapper.selectOne(wrapperChild);
            return dictChild.getName();
        }

    }

    public Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict;
    }
    /**
     * @Author yang
     * @Description //TODO 根据dictCode获取所有的下节节点
     * @Param [dictCode]
     * @return
     **/
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取dictID
        Dict dict = this.getDictByDictCode(dictCode);

        //通过parent_id ==id 获取子节点
        List<Dict> list = this.findChildData(dict.getId());
        return list;
    }

    private boolean isChild(Long id){
        QueryWrapper<Dict> wrapper=new QueryWrapper<>();
        //父节点等于id，查询出子节点
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        //如果查询出的结果大于0，说明有子节点
        return count>0;
    }
}
